
#import <gamekit/gamekit.h>
#import <daymisckit/daymisckit.h>
#import <strings.h>
#import <libc.h>

#define authorEmail [strings valueForStringKey:"Author"]
#define _versionString [strings valueForStringKey:"Version"]

/* static char *stripnl(char *s)
{
	char *p;
	for (p = s; *p; p++)
		if (*p == '\n' || *p == '\r') *p = '\0';
	return s;
}

char *execstr(s)
char *s;
{
	FILE *f = popen(s,"r");
	char *p = s;
	*s = '\0';
	if (f){
		while (fgets(p,256,f))
			stripnl(p), p += strlen(p);
		pclose(f);
	}
	return s;
} */

@implementation InfoController

- init				// make sure that *Panel is nil.
{
	self = [super init];
	infoPanel = nil;
	registerPanel = nil;
	orderFormPanel = nil;
    keyFileName = malloc(strlen([NXApp appDirectory]) + 8);
    // get name of key file (inside app wrapper)
    strcpy(keyFileName, [NXApp appDirectory]);
    strcat (keyFileName, "/key");
	key = malloc(64);
	serialNum = malloc(64);
	strcpy(serialNum, unRegSerial);
	[self readKey];
	return self;
}

- appDidInit:sender	// forwarded by GameBrain
{
	if (!strings) strings = [[NXApp delegate] mainStrings];
	return self;
}

- niftyView { return niftyView; }

- readKey
{ // **** need to check and see if a key is in defaults system if can't get one from the file.
    NXTypedStream *typedStream;
    FILE *testFile;
	char *temp;

    testFile = fopen(keyFileName, "r"); // see if file exists; circumvents
    if (testFile == NULL) {
		if ([strings valueForStringKey:"NotRegistered"])
			strcpy(key, [strings valueForStringKey:"NotRegistered"]);
		else strcpy(key, "No key.");
		return self;
	}
    fclose(testFile);
    typedStream = NXOpenTypedStreamForFile(keyFileName, NX_READONLY);
	NXReadTypes(typedStream, "*", &temp);
	if (temp) { strcpy(key, temp);
	} else {
		if ([strings valueForStringKey:"NotRegistered"]) {
			strcpy(key, [strings valueForStringKey:"NotRegistered"]);
		} else { strcpy(key, "No key."); }
	}
    NXCloseTypedStream(typedStream);

    return self;
}

- writeKey
{ // ***** save the key in the defaults system, too!
	NXTypedStream *typedStream;

	typedStream = NXOpenTypedStreamForFile(keyFileName, NX_WRITEONLY);
	if (!typedStream) {
		NXRunAlertPanel("writeKey",[strings valueForStringKey:"CantReg"],
			NULL, NULL, [strings valueForStringKey:"OK"]);
		return self;
    }
	NXWriteTypes(typedStream, "*", &key);
	NXCloseTypedStream(typedStream);
	return self;
}

- infoPanel		// return the infoPanel, load it if needed.
{
	if( !infoPanel)
		[NXApp loadNibSection:"InfoPanel.nib" owner:self withNames:NO];
	return infoPanel;
}

- registerPanel		// return the registerPanel, load it if needed.
{
	if( !registerPanel)
		[NXApp loadNibSection:"Register.nib" owner:self withNames:NO];
	return registerPanel;
}

- orderFormPanel		// return the orderFormPanel, load it if needed.
{
	if( !orderFormPanel)
		[NXApp loadNibSection:"OrderForm.nib" owner:self withNames:NO];
	return orderFormPanel;
}

- (const char *)versionString
{
	return _versionString;
}

- info:sender		// make the info panel be up there.
{
	[[self infoPanel] orderFront:sender];
	[versionText setStringValue:_versionString];
	[versionDateText setStringValue:[strings valueForStringKey:"VersionDate"]];
	[niftyView start:self]; // will stop automatically on close by
	// using window's delegate method -windowWillClose:
	return self;
}

- readme:sender	// make the README panel be up there.
{
	[[[NXHelpPanel new]
			showFile:"README.rtfd" atMarker:NULL]
			makeKeyAndOrderFront:self];
	return self;
}

- license:sender	// make the license panel be up there.
{
	[[[NXHelpPanel new]
			showFile:"License.rtfd" atMarker:NULL]
			makeKeyAndOrderFront:self];
	return self;
}

- registration:sender
{
	char *tmp2str = malloc(64);

	[self registerPanel]; // make sure nib is loaded
	if ([self notRegistered])
		[[regText setStringValue:[strings valueForStringKey:"Unreg"]]
			setTextGray:NX_WHITE];
	else {
		sprintf(tmp2str, [strings valueForStringKey:"Reg"], serialNum);
		[[regText setStringValue:tmp2str]
			setTextGray:NX_DKGRAY];
	}
	free(tmp2str);
	[[self registerPanel] makeFirstResponder:regNumText];
	if (!strlen(key)) strcpy(key, [strings valueForStringKey:"NotRegistered"]);
	[regNumText setStringValue:key];
	[regNumText selectText:self];
	[NXApp runModalFor:[self registerPanel]];
	return self;
}

- orderForm:sender
{
	[[self orderFormPanel] makeKeyAndOrderFront:sender];
	return self;
}

- (BOOL)notRegistered
{	// determine if the user has registered.
	const char *tmpstr = key;
	char *tmp2str = malloc(64);
	
	if (!tmpstr) {
		[[regText setStringValue:[strings valueForStringKey:"Unreg"]]
			setTextGray:NX_WHITE];
		free(tmp2str);
		return YES;
	}

	if ([self keyOK]) {
		sprintf(tmp2str, [strings valueForStringKey:"Reg"], serialNum);
		[[regText setStringValue:tmp2str]
			setTextGray:NX_DKGRAY];
		free(tmp2str);
		return NO;
	}
		[[regText setStringValue:[strings valueForStringKey:"Unreg"]]
			setTextGray:NX_WHITE];
	free(tmp2str);
	return YES;
}

- (BOOL)keyOK
{	// override to check the "key" variable (a char *) for proper values...
	return YES;
}

- registerGame:sender		// accept registration...or not...
{
	char *tmp2str = malloc(64);
	const char *tmpstr = [regNumText stringValue];
	
	strcpy(key, tmpstr);
	if ([self keyOK]) {
		[self writeKey];
		sprintf(tmp2str, [strings valueForStringKey:"Reg"], serialNum);
		[[regText setStringValue:tmp2str]
			setTextGray:NX_DKGRAY];
	} else {
		[self writeKey];
		[[regText setStringValue:[strings valueForStringKey:"Unreg"]]
			setTextGray:NX_WHITE];
	}
	free(tmp2str);
	[registerPanel orderOut:self];
	[NXApp stopModal];
	return self;
}

- cancelRegistration:sender		// cancel registration modal loop...
{
	[registerPanel orderOut:self];
	[NXApp stopModal];
	return self;
}

- suggestion:sender	// This is pretty much lifted from Opener.
{
	char subj[256]; // w[256] = "whoami";
	char body[4096] = "";

#define call(a,b) [s performRemoteMethod:a with:b length:strlen(b)+1]

    id s = [NXApp appSpeaker];
	int x = 1;
	int doit = NO;
	
	const char *tmpstr = NXGetDefaultValue ([NXApp appName], "Mail");
	
	if (!tmpstr) doit = YES;
	else if (strcmp(tmpstr, "OK")) doit = YES;
	if (doit) x = NXRunAlertPanel([strings valueForStringKey:"Warning"],
		[strings valueForStringKey:"Clobber"],
		[strings valueForStringKey:"OK"],
		[strings valueForStringKey:"OKForever"],
		[strings valueForStringKey:"Abort"]);
		
	if (x == 0) NXWriteDefault ([NXApp appName], "Mail", "OK");
	if (x == -1) return self; // abort

	sprintf(body, [strings valueForStringKey:"MailMessage"],
			[strings valueForStringKey:"AuthorName"], [NXApp appName]);

    NXPortFromName("Mail", NULL); // make sure app is launched
    [[NXApp appSpeaker] setSendPort:NXPortFromName("MailSendDemo", NULL)];

    sprintf(subj,"Comments and suggestions for ``%s'' ",[NXApp appName]);
    strcat(subj,_versionString); strcat(subj, " (");
	strcat(subj,serialNum); strcat(subj,")");
    strcat(body,[NXApp userRealName]); strcat(body,"\n");

    call("setTo:", authorEmail);
    call("setSubject:",subj);
    call("setBody:",body);
    
    return self;
}

- costCalc:sender
{ // override for more useful functions...
	[costText setIntValue:10];
	return self;
}

- printOrderForm:sender	// Do -costCalc and then print orderForm.
{
	[self costCalc:self];
	[[sender window] smartPrintPSCode:sender];
	return self;
}


@end
